package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.AccountInfoRes;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AuthenticationUtils;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.KkdListHeader;
import com.kkd.kkdapp.view.ScrollerLayout;
import com.kkd.kkdapp.view.EditText.FinanceEditText;
import com.kkd.kkdapp.view.ScrollerLayout.OnPullListener;
import com.kkd.kkdapp.view.ScrollerLayout.ScrollStateProvider;
import com.kkd.kkdapp.view.xlistview.XListViewHeader;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

/***
 * 
 * @Name 快乐币购买
 * 
 * @author mty
 * 
 * @Date 2016-11-30 16:45
 * 
 */
public class HappyMoneyBuyActivity extends BaseActivity implements
		OnClickListener {

	private static final int ACCOUNTINFO_CODE_ZERO = 1;
	private static final int ACCOUNTINFO_CODE_ELSE = 2;
	private static final int BUY_SUCCESS = 3;
	private static final int BUY_FAIL = 4;

	private RelativeLayout buy_title_img; // 返回键
	private FinanceEditText centre_ed; // 输入框
	private TextView happyCoinNumber_tv; // 兑换快乐币个数
	private DecimalFormat df = new DecimalFormat("0");
	private DecimalFormat dfTwo = new DecimalFormat("0.01");
	private Dialog loadDialog;
	private TextView balance_tv; // 可用余额
	private TextView happycoin_tv; // 快乐币个数
	private TextView proportion_tv; // 兑换比例
	private int coinExchange = 0; // 兑换比例
	private TextView clause_bt; // 条款
	private String buyCoinLawUrl = ""; // 服务条款URL
	private Button buy_button; // 购买按钮
	private String coinShopUrl; // 快乐商城Url
	private Dialog bsDialog; // 购买成功Dialog
	private Dialog nsfDialog; // 账户余额不足对话框
	private double balance = 0; // 账户余额
	private AccountInfoRes mAccountInfo;
	private Dialog mSinaDialog;
	private ScrollerLayout mScrollView;
	private KkdListHeader mHeaderView;
	private ScrollView nScrollView;
	private boolean dropDownFlag = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ACCOUNTINFO_CODE_ZERO:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				mScrollView.clearState();
				mAccountInfo = (AccountInfoRes) msg.obj;
				lodingData(mAccountInfo);
				break;
			case ACCOUNTINFO_CODE_ELSE:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				mScrollView.clearState();
				showToast(msg.obj.toString());
				break;
			case BUY_SUCCESS:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				buySuccessDialog();
				break;
			case BUY_FAIL:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				Toast.makeText(HappyMoneyBuyActivity.this, msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;

			}
		};
	};

	// 加载数据
	public void lodingData(AccountInfoRes mAccountInfo) {
		// 可用余额
		balance = mAccountInfo.getBalance();
		balance_tv.setText(dfTwo.format(balance));
		centre_ed.setDecimalDigits(0);
		// 快乐币个数
		int coinCount = mAccountInfo.getCoinCount();
		happycoin_tv.setText(coinCount + "个");
		// 兑换比例
		coinExchange = mAccountInfo.getCoinExchange();
		proportion_tv.setText("1元=" + coinExchange + "快乐币");
		// 服务条款URL
		buyCoinLawUrl = mAccountInfo.getBuyCoinLawUrl();
		// 快乐商城Url
		coinShopUrl = mAccountInfo.getCoinShopUrl();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_happy_money_buy);
		initView();
		setListener();
	}

	/****
	 * 初始化控件
	 */
	public void initView() {
		buy_title_img = (RelativeLayout) this.findViewById(R.id.buy_title_img);
		centre_ed = (FinanceEditText) this.findViewById(R.id.centre_ed);
		happyCoinNumber_tv = (TextView) this
				.findViewById(R.id.happyCoinNumber_tv);
		balance_tv = (TextView) this.findViewById(R.id.balance_tv);
		happycoin_tv = (TextView) this.findViewById(R.id.happycoin_tv);
		proportion_tv = (TextView) this.findViewById(R.id.proportion_tv);
		clause_bt = (TextView) this.findViewById(R.id.clause_bt);
		buy_button = (Button) this.findViewById(R.id.buy_button);
		nScrollView = (ScrollView) findViewById(R.id.childScroll);
		mScrollView = (ScrollerLayout) this.findViewById(R.id.mScrollView);
		mScrollView = (ScrollerLayout) findViewById(R.id.mScrollView);
		mHeaderView = new KkdListHeader(this);
		mScrollView.addTopView(mHeaderView);
		mScrollView.setScrollStateProvider(new ScrollStateProvider() {

			@Override
			public boolean canPullUp() {
				return false;
			}

			@Override
			public boolean canPullDown() {
				int scrollY = nScrollView.getScrollY();
				if (scrollY == 0) {
					return true;
				}
				return false;
			}
		});
		mScrollView.setOnPullListener(new OnPullListener() {

			@Override
			public void onPullUp(float pull) {

			}

			@Override
			public void onPullStateChange(byte state) {
				switch (state) {
				case ScrollerLayout.STATUS_IDLE:// 空闲状态
					mHeaderView.setVisibility(View.GONE);
					break;
				case ScrollerLayout.STATUS_PULL_DOWN:// 下拉：不满足hold条件
					mHeaderView.setVisibility(View.VISIBLE);
					mHeaderView.setState(XListViewHeader.STATE_NORMAL);
					break;
				case ScrollerLayout.STATUS_PULL_UP:// 上拉：不满足hold条件
					break;
				case ScrollerLayout.STATUS_UP_HOLD:// 上拉后等待状态
					break;
				case ScrollerLayout.STATUS_DOWN_HOLD:// 下拉后等待状态
					mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
					dropDownFlag = true;
					getAccountInfo();
					break;
				case ScrollerLayout.STATUS_ANIMATING:// 回弹动画状态
					break;
				case ScrollerLayout.STATUS_PULL_DOWN_ENABLE:// 下拉：满足hold条件，松开将hold
					mHeaderView.setState(XListViewHeader.STATE_READY);
					break;
				case ScrollerLayout.STATUS_PULL_UP_ENABLE: // 上拉：满足hold条件，松开将hold
					break;
				default:
					break;
				}
			}

			@Override
			public void onPullDown(float pull) {

			}
		});
	}

	public void setListener() {
		buy_title_img.setOnClickListener(this);
		centre_ed.addTextChangedListener(new InputWatcher());
		clause_bt.setOnClickListener(this);
		buy_button.setOnClickListener(this);
		centre_ed.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_GO) {
					if (buy_button.isEnabled())
						if (yourCreditIsRunningLow()) { // 余额不足
							showNotSufficientFundsDialog();
						} else {
							buyHappyCoin(Long.parseLong(happyCoinNumber_tv
									.getText().toString()),
									Long.parseLong(centre_ed.getText()
											.toString()) * 100);
						}
					return true;
				}
				return false;
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.buy_title_img: // 返回键
			finish();
			break;
		case R.id.clause_bt: // 条款
			if (!"".equals(buyCoinLawUrl) && buyCoinLawUrl != null) {
				Intent intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("url", buyCoinLawUrl);
				startActivity(intent);
			}
			break;
		case R.id.buy_button: // 购买按钮
			if (yourCreditIsRunningLow()) { // 余额不足
				showNotSufficientFundsDialog();
			} else {
				buyHappyCoin(
						Long.parseLong(happyCoinNumber_tv.getText().toString()),
						Long.parseLong(centre_ed.getText().toString()) * 100);
			}
			break;
		default:
			break;
		}

	}

	// 余额不足
	public boolean yourCreditIsRunningLow() {

		if (balance >= Double.parseDouble(centre_ed.getText().toString())) {
			return false;
		} else {
			return true;
		}

	}

	public class InputWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if ("".equals(s.toString())) {
				happyCoinNumber_tv.setText("0");
				buy_button.setEnabled(false);
				buy_button.setClickable(false);
			} else {
				double inputAmount = Double.parseDouble(s.toString());
				happyCoinNumber_tv.setText(""
						+ df.format((inputAmount * coinExchange)));
				if (Long.parseLong(happyCoinNumber_tv.getText().toString()) == 0) {
					buy_button.setEnabled(false);
					buy_button.setClickable(false);
				} else {
					buy_button.setEnabled(true);
					buy_button.setClickable(true);
				}
			}
		}

		@Override
		public void afterTextChanged(Editable s) {

		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		getAccountInfo();
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		if (dropDownFlag) {
			dropDownFlag = false;
		} else {
			loadDialog = DialogUtils.toLoadDialog(this, "加载中...");
		}
		KkdHttpMagager.getInstance().getAccountInfoManager(
				AccountInfoRes.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						AccountInfoRes mAccountInfo = (AccountInfoRes) responseBody;
						Message msg = new Message();
						msg.obj = mAccountInfo;
						msg.what = ACCOUNTINFO_CODE_ZERO;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = ACCOUNTINFO_CODE_ELSE;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	/***
	 * 购买快乐币接口
	 */
	public void buyHappyCoin(long coinCount, long amount) {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "购买中，请等待...");
		KkdHttpMagager.getInstance().buyHappyCoin(coinCount, amount,
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = new Message();
						msg.what = BUY_SUCCESS;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = BUY_FAIL;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	/***
	 * 购买成功Dialog
	 */
	public void buySuccessDialog() {
		if (bsDialog != null) {
			bsDialog.cancel();
			bsDialog = null;
		}
		bsDialog = DialogUtils.buySuccessDialog(this,
				R.drawable.tender_succeed, "购买成功", "我知道了", "去快乐商城",
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.cancel_bt: // 取消
							if (bsDialog != null) {
								bsDialog.dismiss();
							}
							finish();
							break;
						case R.id.confirm_bt: // 确认
							if (bsDialog != null) {
								bsDialog.dismiss();
							}
							finish();
							if (!TextUtils.isEmpty(coinShopUrl)) {
								Intent intent = new Intent(
										HappyMoneyBuyActivity.this,
										KKDWebActivity.class);
								intent.putExtra("url", coinShopUrl);
								startActivity(intent);
							}
							break;
						}
					}
				});
		bsDialog.show();
	}

	/****** 账户余额不足对话框 ************/
	public void showNotSufficientFundsDialog() {
		if (nsfDialog != null) {
			nsfDialog.cancel();
			nsfDialog = null;
		}
		nsfDialog = DialogUtils.notSufficientFundsDialog(this,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.cancel_tv: // 取消
							if (nsfDialog != null) {
								nsfDialog.dismiss();
							}
							break;
						case R.id.recharge_tv: // 充值
							SystemUtils.onEvent(
									"HappyMoneyBuy_Windows_Recharge", 1);
							AuthenticationUtils.getAuthenticationResult(
									HappyMoneyBuyActivity.this, 3,
									RechargeActivity.class);
							nsfDialog.dismiss();
							break;
						}

					}
				}, true);
		nsfDialog.show();
	}

	protected void showSinaDialog() {
		if (mSinaDialog != null) {
			mSinaDialog.cancel();
			mSinaDialog = null;
		}
		try {
			String text = "";

			if (mAccountInfo.getWithholdAuth().getIsSinaPayPassword() == 0) {
				text = mAccountInfo.getWithholdAuth().getPayPasswordTips();
			} else if (mAccountInfo.getWithholdAuth().getIsWithholdAuth() == 0) {
				text = mAccountInfo.getWithholdAuth().getWithholdAuthTips();
			}
			if (!TextUtils.isEmpty(text)) {
				mSinaDialog = DialogUtils.generate2BDialog(this, text, "去设置",
						"再看看", new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();
								Intent intent = new Intent(
										HappyMoneyBuyActivity.this,
										KKDSinaWebActivity.class);
								intent.putExtra("url", mAccountInfo
										.getWithholdAuth()
										.getSinaWithholdAuthUrl());
								intent.putExtra("useTitleName", true);
								intent.putExtra("titleName", "新浪支付");
								startActivityForResult(intent,
										KKDSinaWebActivity.SET_PWD);
							}
						}, new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();
								finish();
							}
						});
				mSinaDialog.show();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		if (bsDialog != null) {
			bsDialog.cancel();
			bsDialog = null;
		}
		if (nsfDialog != null) {
			nsfDialog.cancel();
			nsfDialog = null;
		}
		if (mSinaDialog != null) {
			mSinaDialog.cancel();
			mSinaDialog = null;
		}
	}

}
